<?php
/**
 * certificate signing request model
 *
 * @author raphael seebacher <raphasee@ee.ethz.ch>
 * @version 0.01
 */
class certificate_signing_request extends model {
    protected $csr = NULL;
    protected $certificate_serial_number = NULL;
    protected $signed_certificate = NULL;

    public function __construct($csr) {
        $this->csr = $csr;
    }

    public function sign_request($user) {
        $csr_subject = openssl_csr_get_subject($this->csr);
        if ($csr_subject['CN'] != $user->get_id()) {
            throw new model_exception('CommonName is not valid.');
        }

        $filename = uniqid();
        file_put_contents('../tmp/'.$filename.'.pem', $this->csr);

        $command = '../scripts/certificate_authority/csr_sign.sh '.$filename;
        exec($command, $output, $return);
        $output = implode($output, "\n");

        $pattern_serial_number = '/Serial Number: (?P<serial_number>[0-9]+)/';

        if (!preg_match($pattern_serial_number, $output, $serial_number)) {
            throw new model_exception('CSR has already been signed.');
        }
        else {
            $this->certificate_serial_number = $serial_number['serial_number'];
        }
    }

    public function get_signed_certificate() {
        if ($this->certificate_serial_number == NULL) {
            throw new model_exception('Certificate is not yet signed.');
        }

        $certificate_filename = '../data/certificate_authority/certificates/';
        if ($this->certificate_serial_number<16) {
            $certificate_filename .=
                '0'.strtoupper(dechex($this->certificate_serial_number)).'.pem';
        }
        else {
            $certificate_filename .=
                strtoupper(dechex($this->certificate_serial_number)).'.pem';
        }

        $certificate = file_get_contents($certificate_filename);

        if (openssl_x509_export($certificate, $result)) {
            return $result;
        }
        
        throw new model_exception('Certificate cannot be exported to string.');
    }
}
?>